package com.yaoyanshe.trialfield.network.http

import androidx.annotation.WorkerThread
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.util.concurrent.TimeUnit

/**
 *<p>description:</p>
 *<p>created on: 2020/9/23 20:27</p>
 * @author tck
 * @version v1.3.0
 *
 */

object UploadImage {

    private val client: OkHttpClient by lazy {
        OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .callTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build()
    }

    @WorkerThread
    fun uploadFile(file: File, url: String?): SytResult<Any> {
        if (url.isNullOrEmpty()) {
            return SytResult.error(msg = "url 为空")
        }
        try {
            val requestBody = file.asRequestBody("application/octet-stream".toMediaType())

            val request = Request.Builder()
                    .url(url)
                    .put(requestBody)
                    .build()
            val response = client.newCall(request).execute()
            return if (response.isSuccessful) {
                SytResult.success(data = url)
            } else {
                SytResult.error(msg = response.message)
            }
        } catch (e: Exception) {
            return SytResult.error(msg = "服务器失败：${e.message}")
        }
    }

}